package ttu.idu0080.ryhm103_offerService;

import java.io.IOException;
import java.util.List;

import ttu.idu0080.courierService_client.Courier;
import ttu.idu0080.courierService_client.CourierService_CourierServicePort_Client;
import ttu.idu0080.ryhm103_logger.OrderServicesLogger;

public class OfferServiceImpl implements ryhm103_offerService {
	
	public Offer getOffer(int courier_id, Order order){
		Offer offer=new Offer();
		CourierService_CourierServicePort_Client courierServiceClient=new CourierService_CourierServicePort_Client();
		Courier courier=null;
		int offer_discount_pc=0;
		double offer_discount=0;
		
		try {
			courier = courierServiceClient.getCourierByID(courier_id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Seller seller=order.getSeller();

		
		
		if(isMatchWithAddresses(courier, seller)){
			offer_discount_pc=offer_discount_pc+30;
		}
		
		if(isMatchWithShippingAddresses(courier, order.getShippingAddress())){
			offer_discount_pc=offer_discount_pc+30;
		}
		offer_discount=(double)order.getPriceTotal()-(order.getPriceTotal()*offer_discount_pc)/100;
		
		offer.setOffer_price(offer_discount);
		try {
			OrderServicesLogger.log("OfferService starts", true);
			OrderServicesLogger.log("received courier id:[" + courier_id + "]" +
			" order price: " + offer.getOffer_price() +
			" shipping address country : [" + order.getShippingAddress().getCountry() + "]", false);
			OrderServicesLogger.log("Kullerfirma protsent: [" + courier.getPercentFromOrder()+ "]", false);
			if(isMatchWithShippingAddresses(courier, order.getShippingAddress())){;
			OrderServicesLogger.log("Shipping aadress langeb kokku kullerfirma aadressiga", false);	
			}	
			OrderServicesLogger.log("Offer discount %  ["+ offer_discount_pc +" ]", false);
			OrderServicesLogger.log("Offer: [" + offer.getOffer_id() + "]" + "Offer price: [" + offer.getOffer_price() + "]" + "Aprox. delivery date: [" + offer.getDelivery_time() + "]", false);
			OrderServicesLogger.log("Courierservice ends", true);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		return offer;
	}

	private boolean isMatchWithAddresses(Courier courier, Seller seller){
		boolean match=false;
		for(ttu.idu0080.courierService_client.EntAddress ee: courier.getAddresses()){
			String county=ee.getCounty();
			for(EntAddress ea: seller.getAddresses()){
				if(county.equalsIgnoreCase(ea.getCounty())){
					match=true;
					return match;
				}
			}
		}
		return match;
	}
	
	private boolean isMatchWithShippingAddresses(Courier courier, Address shippingAddress){
		boolean match=false;
		for(ttu.idu0080.courierService_client.EntAddress e: courier.getAddresses()){
			if(e.getCounty().equalsIgnoreCase(shippingAddress.getCounty()));{
				match=true;
				return match;
			}
		}
		return match;
	}
	
}
